// 全局匹配会有lastIndex问题，每次处理一次文本时需要将lastIndex置为0
const defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g
function genProps(attrs) {
    let obj = {};
    for (let i = 0; i < attrs.length; i++) {
        let attr = attrs[i];
        if (attr.name === 'style') {
            let target = {};
            attr.value.split(/;\s*/).forEach(item => {
                let [key, value] = item.split(/:\s*/);
                if (key && value) {
                    target[key] = value.trim();
                }
            })
            attr.value = target;
        }
        obj[attr.name] = attr.value;
    }
    return JSON.stringify(obj);
}

// 处理子元素
function gen(child) {
    if (child.tag === 1) {
        // 是元素
        return generate(child);
    } else {
        let text = child.text;
        // `cc {{aa}} bb {{dd}} ee` => _v('cc'+ _s(aa)+'bb'+_s(dd))
        if (text) {
            let lastIndex = defaultTagRE.lastIndex = 0;
            let match,
                token = [];
            while (match = defaultTagRE.exec(text)) {
                let index = match.index;
                if (index > lastIndex) { // 双花括号前有字符串
                    token.push(JSON.stringify(text.slice(lastIndex, index)));
                }
                token.push(`_s(${match[1]})`);
                lastIndex = index + match[0].length
            }
            // 可能最后还没放入数组
            if (lastIndex < text.length) {
                token.push(JSON.stringify(text.slice(lastIndex)));
            }
            return `_v(${token.join('+')})`;
        }

    }
}

function genChild(children) {
    if (children.length > 0) {
        const res = children.map(item => gen(item));
        return res;
    }
}
export function generate(ast) {
    let children = genChild(ast.children);
    let code = `
        _c('${ast.tagName}', ${ast.attrs.length > 0 ? genProps(ast.attrs) : undefined}${children ? (',' + children) : ''
        })
    `
    return code;
}


/* <div id="app" style="color: orange; background: #008c8c;" class='items'>
prev
<h1>haa {{a}} hee </h1>
next
</div> */

// _c("div", {"id": "app", "style": "{color: orange, background: #008c8c}", class: "items"}, _v(prev), _c("h1", undefined, _v('haa'+_s(a)+'hee'), _v('next'))

// _c('div', { "id": "app", "style": { "color": "orange", " background": "#008c8c" }, "class": "items" }, _v("prev"),
//     _c('h1', undefined, _v("haa" + _s(a) + "hee"))
//     , _v("next"))
